<template>
  <div ref="chartContainer" class="echart-line-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import type { ECharts, EChartsOption } from 'echarts';

// 定义组件 props
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  xAxisUnit: {
    type: String,
    default: ''
  },
  xAxisType: {
    type: String as PropType<'category' | 'value'>,
    default: 'category'
  },
  xAxisData: {
    type: Array<number | string>,
    required: true
  },
  yAxisUnit: {
    type: String,
    default: ''
  },
  seriesData: {
    type: Array<{
      name: string,
      data: number[],
      symbol?: string,
      symbolSize?: number,
      color?: string
    }>,
    required: true
  },
  showToolbar: {
    type: Boolean,
    default: true
  },
  showZoom: {
    type: Boolean,
    default: true
  }
});

type SeriesItem = {
  name: string;
  data: number[];
  symbol?: string;
  symbolSize?: number;
  color?: string;
};

// 定义组件 emits
const emit = defineEmits<{
  (e: 'pointClick', params: any): void
}>();

// 图表容器引用
const chartContainer = ref<HTMLDivElement | null>(null);
// 图表实例引用
let chartInstance: ECharts | null = null;

// 窗口大小变化处理函数
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 初始化图表
const initChart = () => {
  if (!chartContainer.value || !props.xAxisData.length || !props.seriesData.length) {
    return;
  }

  // 准备图表配置
  const option: EChartsOption = {
    title: {
      text: props.title,
      left: 'center',
      textStyle: {
        fontSize: 18
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any) {
        //let result = `${params[0].name}`;
        const timestamp = params[0].name;
        const date = new Date(timestamp / 1000); // 微秒转毫秒
        const formattedDate = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}.${(timestamp % 1000000).toString().padStart(6, '0')}`;
        let result = formattedDate;
        params.forEach((param: any) => {
          result += `<br/>${param.marker} ${param.seriesName}: ${param.value}`;
        });
        return result;
      }
    },
    legend: {
      data: props.seriesData.map(item => item.name),
      bottom: props.showZoom ? 30 : 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: props.showZoom ? '15%' : '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: props.xAxisType,
      boundaryGap: false,
      name: props.xAxisUnit ? `X-axis (${props.xAxisUnit})` : 'X-axis',
      nameLocation: 'middle',
      nameGap: 30,
      data: props.xAxisType === 'category' ? props.xAxisData : undefined,
      axisLabel: {
        rotate: 0,
        formatter: (value: number) => {
          const timestamp = value
          const date = new Date(timestamp / 1000); // 微秒转毫秒
          const formattedDate = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
          let result = formattedDate;
          return result
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: '#eee'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: props.yAxisUnit ? `Y-axis (${props.yAxisUnit})` : 'Y-axis',
      nameLocation: 'middle',
      nameGap: 40,
      splitLine: {
        show: true,
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: props.seriesData.map((item: SeriesItem) => ({
      name: item.name,
      type: 'line',
      data: item.data,
      symbol: item.symbol || 'circle',
      symbolSize: item.symbolSize || 8,
      itemStyle: {
        color: item.color || undefined
      },
      lineStyle: {
        width: 2
      },
      emphasis: {
        focus: 'series',
        itemStyle: {
          borderWidth: 2
        }
      },
      axisPointer: {
        show: true
      },
      connectNulls: true ,  // 不相邻的点能连接起来
    })),
    toolbox: props.showToolbar ? {
      feature: {
        saveAsImage: {
          title: 'Save Image',
          pixelRatio: 2
        },
        dataZoom: {
          title: {
            zoom: 'zoom enable',
            back: 'zoom cancel'
          }
        },
        restore: {
          title: 'restore'
        }
      },
      right: 10
    } : undefined,
    dataZoom: props.showZoom ? [{
      type: 'slider',
      show: true,
      xAxisIndex: [0],
      bottom: 0
    }, {
      type: 'inside',
      xAxisIndex: [0]
    }] : undefined
  };

  // 创建图表实例
  chartInstance = echarts.init(chartContainer.value);

  // 设置图表配置
  chartInstance.setOption(option);

  // 绑定点击事件
  chartInstance.on('click', (params: any) => {
    emit('pointClick', params);
  });
};

// 监听 props 变化，更新图表
watch([
  () => props.title,
  () => props.xAxisUnit,
  () => props.xAxisType,
  () => props.xAxisData,
  () => props.yAxisUnit,
  () => props.seriesData,
  () => props.showToolbar,
  () => props.showZoom
], () => {
  if (chartInstance) {
    initChart();
  }
});

// 组件挂载时初始化图表和事件监听
onMounted(() => {
  nextTick(() => {
    initChart();
    window.addEventListener('resize', handleResize);
  });
});

// 组件卸载时清理图表和事件监听
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped lang="scss">
.echart-line-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
  // 保持与aewave.vue相似的样式
  box-sizing: border-box;
}

// 自定义tooltip样式，使其与aewave.vue接近
:deep(.echarts-tooltip) {
  border-radius: 4px;
  border: 1px solid #ddd;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 8px;
  background-color: rgba(255, 255, 255, 0.95);
}
</style>
